package com.fau.sd.ws;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@ServerEndpoint("/ss")
public class WebSocketServer {
	private static final Log log = LogFactory.getLog(WebSocketServer.class);
	
	private static Map<String, Session> users = new ConcurrentHashMap<String, Session>();
	private String uid;

	@OnMessage
	public void onMessage(String message, Session session) throws IOException,
			InterruptedException {
		uid = message;
		users.put(message, session);
	}

	@OnOpen
	public void onOpen() {
		System.out.println("Client connected");
	}

	@OnClose
	public void onClose() {
		users.remove(uid);
		System.out.println("Connection closed");
	}
	
	@OnError
	public void onError(Throwable t) {
		log.error("WebSocket Error:" + t.toString(), t);
	}
	
	public static void send(String uid, String msg) throws IOException {
		Session session = users.get(uid);
		if(null == session) return;
		try {
			synchronized (session) {
				session.getBasicRemote().sendText(msg);
			}
		} catch(IOException e) {
			log.debug("WebSocket Error: Failed to send message to client", e);
			users.remove(uid);
			try {
				session.close();
			} catch(IOException e1) {
				
			}
		}
	}
}
